import { Component, ViewChild } from '@angular/core';
import { NavController, Slides, IonicPage} from 'ionic-angular';

//声明一个Swiper对象，是全局的引用
declare var Swiper;
@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  swiper: any;
  //ViewChild传入一个字符串contentSlides，变量contentSlides接收。其它不变
  @ViewChild('contentSlides') contentSlides: Slides;
  menus: Array<string> = ['菜单', '菜单', '菜单', '菜单']
  constructor(public navCtrl: NavController) {

  }
  //当页面加载的时候触发，只触发一次，当有缓存的的时候，打开页面时不在加载
  ionViewDidLoad() {
    this.initSwiper();
  }
  //初始化swiper
  initSwiper() {
    this.swiper = new Swiper('.pageMenuSlides .swiper-container', {
      //设置slider容器能够同时显示的slides数量(
      slidesPreView: 4,
      //slide之间的距离（单位px）
      spaceBetween: 0,
      //断点设定：根据屏幕宽度设置某参数为不同的值
      breakpoints: {
        1024: {
          slidesPerView: 4,
          spaceBetween: 0
        },
        768: {
          slidesPerView: 4,
          spaceBetween: 0
        },
        640: {
          slidesPerView: 4,
          spaceBetween: 0
        },
        320: {
          slidesPerView: 4,
          spaceBetween: 0
        }
      }
    });
  }
  //选择菜单
  selectPageMenu(index) {
    this.setStyle(index);
    //切换页面
    this.contentSlides.slideTo(index);
  }
  //选择菜单之后设置菜单样式
  setStyle(index) {
    //得到菜单的个数
    var slides = document.getElementsByClassName('pageMenuSlides')[0].getElementsByClassName('swiper-slide');
    //给所有的菜单都设置上swiper-slide样式
    if (index < slides.length) {
      for (var i = 0; i < slides.length; i++) {
        var s = slides[i];
        s.className = "swiper-slide";
      }
      //给当前菜单设置成这个样式
      slides[index].className = "swiper-slide bottomLine";
    }
  }

  slideChanged() {
    //getActiveIndex()获得当前页面的index
    let index = this.contentSlides.getActiveIndex();
    this.setStyle(index);
    //s切换菜单
    this.swiper.slideTo(index, 300);
  }
}
